package com.wn.quality.web;


import com.wn.common.*;
import com.wn.entity.Hr;
import com.wn.entity.Nonconformance;
import com.wn.quality.openfeign.ActivitiFeignClient;
import com.wn.quality.service.NonconformanceService;
import com.wn.quality.vo.NonconformanceVo;
import com.wn.utils.OssManagerUtil;
import com.wn.validation_group.NcrAddGroup;
import com.wn.validation_group.NcrUpdateGroup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Min;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author wuqingting
 * @date 2022/10/19
 */
@RestController
@RequestMapping("/quality/ncr")
@Slf4j
@Validated//增加注解后,下方的方法中的参数可以直接使用注解进行参数校验
public class NonconformanceController {
    @Autowired
    private NonconformanceService nonconformanceService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private ActivitiFeignClient activitiFeignClient;

    @RequestMapping("/upload")
    public ResponseEntity upload(MultipartFile file) {
        String url = null;
        try {
            String filename = file.getOriginalFilename();
            filename= UUID.randomUUID().toString().replace("-","")+"."+filename;
            url = OssManagerUtil.uploadImage(filename,file.getInputStream().available(),file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity("400","fail","文件上传失败");
        }

        return new ResponseEntity(url);
    }

    @RequestMapping("/add") //使用消息队列添加
    public ResponseEntity add(@RequestBody @Validated(NcrAddGroup.class) Nonconformance nonconformance, HttpServletRequest request){
        //nonconformanceService.add(nonconformance);
        ActivitiStartEntity startEntity = new ActivitiStartEntity();
        startEntity.setProcessDefinitionKey("ncrId");
        startEntity.setAssignee("user1");
        String workNumber = request.getHeader("userWorkNumber");
        startEntity.setUser(workNumber);

        ResponseEntity responseEntity = activitiFeignClient.startInstance(startEntity);//调用流程微服务

        if (responseEntity.getCode().equals("400")){
            return ResponseEntity.fail;
        }

        int userId = Integer.parseInt(request.getHeader("userId"));
        Hr hr = new Hr();
        hr.setId(userId);
        nonconformance.setUser(hr);
        nonconformance.setActivitiInstanceId((String) responseEntity.getData());//存入流程开启后的实例id
        rabbitTemplate.convertAndSend("qualityExchange","ncr",nonconformance);//将消息发送到交换机
        return ResponseEntity.success;
    }

    @RequestMapping("/initiateProcess") //缓存查询
    public ResponseEntity initiateProcess(@RequestBody ActivitiCompleteEntity entity,HttpServletRequest request){
        String workNumber = request.getHeader("userWorkNumber");
        entity.setCurrUser(workNumber);
        activitiFeignClient.completeTask(entity);

        return ResponseEntity.success;
    }

    @RequestMapping("/getById/{id}") //缓存查询
    public ResponseEntity getById(@PathVariable @Min(1) int id){
        String key="ncr:"+id; //自定义生成id
        Nonconformance nonconformance = (Nonconformance) redisTemplate.opsForValue().get(key);//从redis中获取
        log.debug("缓存查询:{}",key);
        if (nonconformance==null){//若缓存中没有,则新建缓存
            nonconformance = nonconformanceService.getById(id);//查询数据库
            redisTemplate.opsForValue().set(key,nonconformance,600, TimeUnit.SECONDS);//存入缓存并设置过期时间
            log.debug("缓存建立:{}",key);
        }
        return new ResponseEntity(nonconformance);
    }

    @RequestMapping("/update")
    public ResponseEntity update(@RequestBody @Validated(NcrUpdateGroup.class) Nonconformance nonconformance){
        nonconformanceService.update(nonconformance);
        return ResponseEntity.success;
    }

    @RequestMapping("/del/{id}")
    public ResponseEntity update(@PathVariable int id){
        nonconformanceService.delete(id);
        return ResponseEntity.success;
    }

    @RequestMapping("/history/{instanceId}")
    public ResponseEntity getHistory(@PathVariable String instanceId){
        ResponseEntity<List<ActivitiInstanceHistory>> responseEntity = activitiFeignClient.historyInfo(new ActivitiHistoryInfoEntity(instanceId));
        return responseEntity;
    }

    @RequestMapping("/getPageByCondition")
    public ResponseEntity getByCondition(@RequestBody NonconformanceVo nonconformanceVo){
        String key="ncr:"+nonconformanceVo.toString(); //自定义生成id
        PageBean<Nonconformance> pageBean = (PageBean<Nonconformance>) redisTemplate.opsForValue().get(key);//从redis中获取
        log.debug("缓存查询:{}",key);
        if (pageBean==null){//若缓存中没有,则新建缓存
            pageBean = nonconformanceService.getPageByCondition
                    (nonconformanceVo.getNonconformance(), nonconformanceVo.getCurrPage(), nonconformanceVo.getPageSize());//查询数据库
            //根据每个单据的实例id查询流程状态
            for (Nonconformance nonconformance : pageBean.getData()) {
                ResponseEntity<List<ActivitiInstanceHistory>> responseEntity =
                        activitiFeignClient.historyInfo(new ActivitiHistoryInfoEntity(nonconformance.getActivitiInstanceId()));
                List<ActivitiInstanceHistory> list = responseEntity.getData();
                nonconformance.setActivitiState(list.get(list.size()-1).getActivitiName());//将最后一步流程的名称存入实体类,用于前台显示
            }
            redisTemplate.opsForValue().set(key,pageBean,600, TimeUnit.SECONDS);//存入缓存并设置过期时间
            log.debug("缓存建立:{}",key);
        }

        return new ResponseEntity(pageBean);
    }

}
